package com.example.nonameaa.service.impl;

import com.example.nonameaa.Common.ServiceException;
import com.example.nonameaa.utils.TokenUtils;
import com.example.nonameaa.entity.User;
import com.example.nonameaa.mapper.UserMapper;
import com.example.nonameaa.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author NoName
 * @since 2024-09-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User loginUser(User user) {

      User dbuser =  userMapper.selectByUsername(user.getUsername());
      if(dbuser == null){
          throw new ServiceException("用户名或密码错误");
      }
      if(!user.getPassword().equals(dbuser.getPassword())){
          throw new ServiceException("用户名或密码错误");
      }
        String token = TokenUtils.createToken(dbuser.getId().toString(), dbuser.getPassword());
        dbuser.setToken(token);
        return dbuser;
    }

    @Override
    public User register(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
        return user;
    }

    @Override
    public void resetPassword(User user){
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户不存在");
        }
        if (!user.getPhone().equals(dbUser.getPhone())) {
            throw new ServiceException("验证错误");
        }
        dbUser.setPassword("123");   // 重置密码
        userMapper.updateById(dbUser);
    }



}
